

package com.demo.exception;


import common.constant.HttpStatus;
import common.exception.RRException;
import common.utils.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class RRExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public Result handleRRException(RRException e) {
        e.printStackTrace();
        Result response = new Result();
        response.setCode(e.getCode());
        response.setMsg(e.getMessage());
        return response;
    }


    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        Result response = new Result();
        response.setCode(HttpStatus.ERROR);
        response.setMsg("未知异常,请联系管理员");
        return response;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        e.printStackTrace();
        String message = e.getAllErrors().get(0).getDefaultMessage();
        Result response = new Result();
        response.setCode(HttpStatus.ERROR);
        response.setMsg(message);
        return response;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        Result response = new Result();
        response.setCode(HttpStatus.ERROR);
        response.setMsg(message);
        return response;
    }
}
